package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hangwei.paperless.adapter.HomeNewAdapter;
import com.hangwei.paperless.model.bean.ServerVersion;
import com.hangwei.paperless.model.bean.Sheet;
import com.hangwei.paperless.model.bean.SheetType;
import com.hangwei.paperless.model.entity.TokenReset;
import com.hangwei.paperless.presenter.HomePresenter;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.Density;
import com.hangwei.paperless.view.HomeTableTitle;
import com.hangwei.paperless.widget.HomePopupWindow;
import com.hangwei.paperless.zxing.QRCodeScanActivity;
import com.twelve.all.base.UpdateVersionActivity;
import com.twelve.all.bean.ClearBottom;
import com.twelve.all.net.API;
import com.twelve.all.net.CallBack;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.NotFastClickListener;
import com.twelve.all.utils.PackageUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class HomeActivity extends UpdateVersionActivity {

    //pop里面的文字
//    private TextView mTvType;
//    private RelativeLayout mRlChoose;
    private LinearLayout mLlUser;
    private String mSheetTypeId;
    private EditText mEtNum;
    //    private HomeAdapter mAdapter;
//    private List<SheetType> mTypeList;
    private boolean logout;
    private HomeNewAdapter mHomeNewAdapter;
    private HomePresenter mHomePresenter;
    private boolean firstLoad = true;
    private ImageView mLlEPA;
    private HomePopupWindow mPopupWindow;

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTokenReset(TokenReset event) {
        ToastUtil.showCenterToast("登陆已过期，请重新登陆！");
        Intent intent10 = new Intent(HomeActivity.this, LoginActivity.class);
        intent10.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent10);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClearBottom(ClearBottom event) {
       hideSystemBar();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_1);
        EventBus.getDefault().register(this);
        TextView tvVersion = findViewById(R.id.tvVersion);
        tvVersion.setText(PackageUtil.getLocalVersionName(HomeActivity.this));
        mLlUser = findViewById(R.id.llUser);
        SimpleDraweeView ivHead = findViewById(R.id.ivHead);
        ivHead.setImageURI(API.BASE_URL + SPUtil.getString(SPKey.Account.USER_HEAD));
        TextView tvUserName = findViewById(R.id.tvUserName);
        String userName = SPUtil.getString(SPKey.Account.USER_NAME, "");
        tvUserName.setText(userName);
        mLlEPA = findViewById(R.id.llEPA);
        mEtNum = findViewById(R.id.etNum);
        ImageView ivScan = findViewById(R.id.ivScan);
        ImageView tvSearch = findViewById(R.id.tvSearch);
        LinearLayout llTitle = findViewById(R.id.llTitle);
        HomeTableTitle homeTableTitle = new HomeTableTitle(this, llTitle);
        homeTableTitle.setL(new HomeTableTitle.OrderByListener() {
            @Override
            public void onOrderBy(String pageOrderName, String pageOrderBy) {
                mHomePresenter.setPageOrderName(pageOrderName);
                mHomePresenter.setPageOrderBy(pageOrderBy);
                LoadingDialog loadingDialog = new LoadingDialog(HomeActivity.this);
                loadingDialog.show();
                mHomePresenter.refresh(new CallBack<List<Sheet>>() {
                    @Override
                    public void onCompleted(List<Sheet> sheets) {
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                    }
                });
            }
        });
        llTitle.addView(homeTableTitle.getInflate());
        ivScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23 &&
                        ContextCompat.checkSelfPermission(HomeActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                    ActivityCompat.requestPermissions(HomeActivity.this,
                            new String[]{
                                    Manifest.permission.CAMERA
                            }, 100);
                else startActivity(new Intent(HomeActivity.this, QRCodeScanActivity.class));
            }
        });
        SwipeRefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        mAdapter = new HomeAdapter(null);
        mHomeNewAdapter = new HomeNewAdapter(null);
        recyclerView.setAdapter(mHomeNewAdapter);
        mHomePresenter = new HomePresenter(refreshLayout, mHomeNewAdapter);
        LoadingDialog dialog = new LoadingDialog(this);
        dialog.show();
        mHomePresenter.refresh(new CallBack<List<Sheet>>() {
            @Override
            public void onCompleted(List<Sheet> sheets) {
                dialog.dismiss();
                firstLoad = false;
            }

            @Override
            public void onError() {
                dialog.dismiss();
            }
        });
        recyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.itemView) {
                    List<Sheet> list = adapter.getData();
                    Sheet sheet = list.get(position);
//                    switch (sheet.number) {
//
//                    }
                    Intent intent = new Intent();
                    if ("GeneralRoutingSheet".equals(sheet.sheetTypeNumber)) {
                        intent.setClass(HomeActivity.this, MainRepairActivity.class);
                    } else if ("RoutingSheet".equals(sheet.sheetTypeNumber)) {
                        intent.setClass(HomeActivity.this, SubRepairActivity.class);
                        intent.putExtra("isLotDataSheet", sheet.isLotDataSheet);
                    } else if ("ModifyRoutingSheet".equals(sheet.sheetTypeNumber)) {
                        intent.setClass(HomeActivity.this, MainRepairActivity.class);
                    }
                    intent.putExtra("id", sheet.id);
                    intent.putExtra("woNo", sheet.woNo);
                    intent.putExtra("pwoNo", sheet.pwoNo);
                    intent.putExtra("pn", sheet.pn);
                    intent.putExtra("sn", sheet.sn);
                    intent.putExtra("description", sheet.description);
                    intent.putExtra("step", sheet.curExStep);
                    startActivity(intent);
                }
            }
        });


//        mRlChoose = findViewById(R.id.rlChoose);
//        mTvType = findViewById(R.id.tvType);
//        mRlChoose.setOnClickListener(mListener);
        mLlUser.setOnClickListener(mListener);
//        ivScan.setOnClickListener(mListener);
        tvSearch.setOnClickListener(mListener);
        mLlEPA.setOnClickListener(mListener);
        loadServerVersion();
//        loadData();
    }

    @Override
    public void onResume() {
        super.onResume();
//        loadData();
        if (!firstLoad && mHomePresenter != null)
            mHomePresenter.refresh();
    }

    private void loadData() {
        final LoadingDialog dialog = new LoadingDialog(this);
        dialog.show();
        final String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getSheetTypeList(userId, new CallBack<List<SheetType>>() {
            @Override
            public void onCompleted(List<SheetType> sheetTypes) {
//                mTypeList = sheetTypes;
//                mTypeList.add(0, new SheetType("全部工卡", true));
                dialog.dismiss();
//                for (SheetType sheetType : sheetTypes) {
//                    if ("GeneralRoutingSheet".equals(sheetType.number)) {
//                        sheetType.checked = true;
//
//                    }
//                }
            }

            @Override
            public void onError() {
                dialog.dismiss();
            }
        });
        mSheetTypeId = "";
//        mTvType.setText(Tools.checkedString("全部工卡"));
        loadList();
    }

    private void loadList() {
        final LoadingDialog dialog = new LoadingDialog(this);
        dialog.show();
        final String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getAllTaskList(userId, mSheetTypeId, "", new CallBack<List<Sheet>>() {
            @Override
            public void onCompleted(List<Sheet> sheets) {
                dialog.dismiss();
//                mAdapter.setNewData(sheets);
            }

            @Override
            public void onError() {
                dialog.dismiss();
            }
        });
    }

    private NotFastClickListener mListener = new NotFastClickListener() {
        @Override
        protected void isNotFastClick(View v) {
            switch (v.getId()) {
                case R.id.tvTypeName:

                    break;
                case R.id.llUser:
                    final PopupWindow popupWindow = new PopupWindow(HomeActivity.this);
                    View inflate = LayoutInflater.from(HomeActivity.this).inflate(R.layout.pop_home_user, null);
                    inflate.findViewById(R.id.llLogout).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
//                            SPUtil.setString(SPKey.Account.PWD, ""); //清除本地保存的密码
//                            SPUtil.setString(SPKey.Account.APP_ID, "");
//                            SPUtil.setString(SPKey.Account.TOKEN, "");
                            ToastUtil.showToast("已退出登录");
                            Intent intent10 = new Intent(HomeActivity.this, LoginActivity.class);
                            intent10.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent10);
                        }
                    });
                    popupWindow.setContentView(inflate);
                    popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setBackgroundDrawable(new ColorDrawable());
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setFocusable(true);
                    popupWindow.showAsDropDown(mLlUser, Density.dip2px(HomeActivity.this, -15f), Density.dip2px(HomeActivity.this, 1f));
                    break;
//                case R.id.rlChoose:
//                    final PopupWindow window = new PopupWindow(HomeActivity.this);
//                    View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.pop_home_choose, null);
//                    RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
//                    recyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
//                    recyclerView.setAdapter(new HomeChooseAdapter(mTypeList) {
//                        @Override
//                        protected void onAdapterItemClick(int position) {
//                            mSheetTypeId = mTypeList.get(position).id;
//                            mTvType.setText(Tools.checkedString(mTypeList.get(position).name));
//                            loadList();
//                            window.dismiss();
//                        }
//                    });
//                    window.setContentView(view);
//                    window.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
//                    window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//                    window.setBackgroundDrawable(new ColorDrawable());
//                    window.setOutsideTouchable(true);
//                    window.setFocusable(true);
//                    window.showAsDropDown(mRlChoose, Density.dip2px(HomeActivity.this, 8f), Density.dip2px(HomeActivity.this, 3f));
//                    break;
                case R.id.tvSearch:
                    String key = mEtNum.getText().toString().trim();
                    mHomePresenter.setWoNo(key);
                    final LoadingDialog loadingDialog = new LoadingDialog(HomeActivity.this);
                    loadingDialog.show();
                    mHomePresenter.refresh(new CallBack<List<Sheet>>() {
                        @Override
                        public void onCompleted(List<Sheet> sheets) {
                            loadingDialog.dismiss();
                        }

                        @Override
                        public void onError() {
                            loadingDialog.dismiss();
                        }
                    });
//                    StaticPresenter.getRoutingSheetByKeyword(SPUtil.getString(SPKey.Account.USER_ID), mSheetTypeId, key, new CallBack<List<Sheet>>() {
//                        @Override
//                        public void onCompleted(List<Sheet> sheets) {
//                            loadingDialog.dismiss();
//                            if (sheets != null && sheets.size() > 0) {
//                                mHomeNewAdapter.setNewData(sheets);
//                            } else {
//                                ToastUtil.showCenterToast("未搜索到对应工卡！");
//                            }
//                        }
//
//                        @Override
//                        public void onError() {
//                            loadingDialog.dismiss();
//                        }
//                    });
                    break;
                case R.id.llEPA:
                    if (mPopupWindow == null)
                        mPopupWindow = new HomePopupWindow(HomeActivity.this, true) {
                            @Override
                            public void goEPA() {
                                if (mPopupWindow.isShowing())mPopupWindow.dismiss();
                                startActivity(new Intent(HomeActivity.this,EngTreatmentActivity.class));
                            }

                            @Override
                            public void goProcess() {
                                if (mPopupWindow.isShowing())mPopupWindow.dismiss();
                                startActivity(new Intent(HomeActivity.this,ProcessListActivity.class));
                            }
                        };
                    mPopupWindow.showAsDropDown(mLlEPA, Density.dip2px(HomeActivity.this, -105f), Density.dip2px(HomeActivity.this, 1f));
                    break;
            }
        }
    };

    protected void loadServerVersion() {
        StaticPresenter.getServerVersion("pad.workshop", new CallBack<ServerVersion>() {
            @Override
            public void onCompleted(ServerVersion data) {
                SPUtil.setString(SPKey.VERSION, data.ver);
                content = "\n" + "已有新的版本了，请更新后再使用\n";
                url = API.BASE_URL + "download/paperless.apk";//安装包下载地址
                wgt = data.wgt;
//                description = data.description;
                String serverVersion = data.ver;
                mServerVersion = serverVersion;
                String localVersionName = PackageUtil.getLocalVersionName(HomeActivity.this);
                boolean b = serverVersion.compareTo(localVersionName) > 0;
                if (b) {
                    LogUtil.d(serverVersion);
                    mWhich = 0;
                    strorageTask();
                }
            }

            @Override
            public void onError() {

            }
        });
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        super.onPermissionsDenied(requestCode, perms);
        if (requestCode == 100)
            ToastUtil.showCenterToast("无权限！");
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        super.onPermissionsGranted(requestCode, perms);
        if (requestCode == 100) {
            Intent intent = new Intent(HomeActivity.this, QRCodeScanActivity.class);
            intent.putExtra("type", 0);
            startActivity(intent);
        }
    }

    @Override
    public void finish() {
        if (logout) {

            super.finish();
            System.exit(0);
        } else {
            logout = true;
            ToastUtil.showCenterToast("再按一次退出应用");
            App.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    logout = false;
                }
            }, 2000);
        }
    }

}
